package com.zsc.wxm.ysh.anjo.member.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.wxm.ysh.anjo.member.mapper.LoginLogMapper;
import com.zsc.wxm.ysh.anjo.member.model.LoginLog;
import com.zsc.wxm.ysh.anjo.member.model.Member;
import com.zsc.wxm.ysh.anjo.member.service.LoginLogService;
import com.zsc.wxm.ysh.anjo.result.PageResult;
import com.zsc.wxm.ysh.anjo.service.base.model.member.qo.LoginLogQuery;
import com.zsc.wxm.ysh.anjo.utils.IpUtil;
import com.zsc.wxm.ysh.anjo.utils.LocationUtil;
import com.zsc.wxm.ysh.anjo.utils.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author playmaker
 * @since 2021-01-04
 */
@Service
@Slf4j
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> implements LoginLogService {

    @Resource
    private LoginLogMapper loginLogMapper;

    @Override
    public void saveLoginLog(HttpServletRequest request, Member member) {
        LoginLog loginLog = new LoginLog();
        String city = LocationUtil.getLocationCity(request);
        loginLog.setAddress(StringUtils.isBlank(city) ? "定位失败" : city);
        loginLog.setLoginIp(IpUtil.getIpAddr(request));
        loginLog.setLoginTime(LocalDateTime.now());
        loginLog.setMemberId(member.getId());
        loginLog.setUsername(member.getUsername());
        this.save(loginLog);
    }

    @Override
    public PageResult listPage(LoginLogQuery query) {
        Page<LoginLog> page = new Page<>(query.getCurrPage(), query.getPageSize());
        LambdaQueryWrapper<LoginLog> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.orderByDesc(LoginLog::getLoginTime);
        //查询条件
        if (StrUtil.isNotBlank(query.getAddress())) {
            queryWrapper.like(LoginLog::getAddress, query.getAddress());
        }
        if (query.getLoginTimeStart() != null) {
            queryWrapper.ge(LoginLog::getLoginTime, query.getLoginTimeStart());
        }
        if (query.getLoginTimeEnd() != null) {
            queryWrapper.le(LoginLog::getLoginTime, query.getLoginTimeEnd());
        }
        page = loginLogMapper.selectPage(page, queryWrapper);
        PageUtil pageUtil = new PageUtil(page);
        log.info("总条数：{}", pageUtil.getTotal());
        return PageResult.ok(pageUtil.getList(), pageUtil.getTotal());
    }
}
